package com.example.demo.controller;

import com.example.demo.common.JWTUtil;
import com.example.demo.common.JsonResult;
import com.example.demo.entity.Users;
import com.example.demo.service.UsersService;
import com.example.demo.vo.UsersVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController   //用于标注控制层组件，将函数的返回值填入响应体中
@RequestMapping("/users") //用于映射web请求，@PostMapping，@GetMapping是它的两种特例，表示不同的请求方式

public class UsersController {

    @Autowired  //用于实现依赖注入，可以应用于构造函数、字段、以及配置方法上，以实现自动装配功能。
    UsersService service;

    @ApiOperation(value = "添加一条用户信息（注册）") //用于描述Api操作，value属性提供对该操作的描述，用于生成Api文档
    @PostMapping("register") //结合了@RequestMapping和method=post，用于处理post请求
    public JsonResult<Object> register(@ApiParam(name = "users",value = "users",required = true) @RequestBody Users users){
         //描述Api参数，name指定参数名，value提供参数描述，required指明参数是否必须
        //将HTTP请求正文（body）绑定到方法的参数上，当需要接收客户端发送的JSON或XML格式的数据，并将其转换为Java对象时用@RequestBody
        try{
            int r = service.register(users);
            if(r > 0){
                return JsonResult.ok();
            }else{
                return JsonResult.fail(5001,"用户添加失败！！");
            }
        }catch (Exception e){
            e.printStackTrace(); //打印
            return JsonResult.fail();
        }
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public JsonResult login(@ApiParam(name = "username",value = "用户名",required = true)@Param("username") String username,
                            @ApiParam(name = "pwd",value = "密码",required = true )@Param("pwd") String pwd){
        //@Param，MyBatis注解，将方法参数名称与查询的参数名称进行关联
        Users users = service.findUsers(username,pwd);  //调用方法查找用户名和密码
        if(users == null){
            return JsonResult.fail(4001,"用户名或密码错误！！");
        }
        String token = JWTUtil.getToken(users,1); //获取token
        return JsonResult.ok(token,users);
    }

    @ApiOperation(value = "管理员查询全部用户的信息")
    @PostMapping("findAll")
    public JsonResult<List<UsersVO>> findAll(String token)
    {
        if(!JWTUtil.verify(token)){
            return JsonResult.fail(5001,"非法访问！！");
        }
        else{
            Users u1 = JWTUtil.parseToken(token);
            Users users = service.findUsers(u1.getUsername(),u1.getPwd());
            if(users.getRole().equals("管理员")){
                List<UsersVO> list = service.findAll();
                return JsonResult.ok(list);
            }
            return JsonResult.fail(5001,"非管理员访问！！");
        }
    }

    @ApiOperation(value = "根据用户姓名查询用户信息")
    @PostMapping("findByName")
    public JsonResult<Users> findByName(@ApiParam(name = "name",value = "用户姓名",required = true)String name,
                                        @ApiParam(name = "token",value = "token",required = true) String token){
        try{
            if(!JWTUtil.verify(token)){
                return JsonResult.fail(5001,"非法访问！！");
            }
            else{
                Users u1 = JWTUtil.parseToken(token);
                Users users = service.findUsers(u1.getUsername(),u1.getPwd());
                if(users.getRole().equals("管理员")){
                    Users user = service.findByName(name);
                    return JsonResult.ok(user);
                }
                return JsonResult.fail(5001,"非管理员访问！！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.fail(5000, "服务器内部错误，更新操作失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "根据id删除用户信息")
    @PostMapping("delete")
    public JsonResult<Boolean> deleteById(Integer id,String token){
        if(!JWTUtil.verify(token)){
            return JsonResult.fail(5001,"非法访问！！");
        }
        else{
            Users u1 = JWTUtil.parseToken(token);
            Users users = service.findUsers(u1.getUsername(),u1.getPwd());
            if(users.getRole().equals("管理员")){
                int r = service.deleteById(id);
                return JsonResult.ok(r > 0);
            }
            return JsonResult.fail(5001,"非管理员访问！！");
        }
    }

    @ApiOperation(value = "根据用户姓名删除用户信息")
    @PostMapping("deleteByName")
    public JsonResult deleteByName(@ApiParam(name = "name",value = "用户姓名",required = true)String name,
                                   @ApiParam(name = "token",value = "token",required = true) String token){
        try{
            if(!JWTUtil.verify(token)){
                return JsonResult.fail(5001,"非法访问！！");
            }
            else{
                Users u1 = JWTUtil.parseToken(token);
                Users users = service.findUsers(u1.getUsername(),u1.getPwd());
                if(users.getRole().equals("管理员")){
                    int r = service.deleteByName(name);
                    return JsonResult.ok(r > 0);
                }
                return JsonResult.fail(5001,"非管理员访问！！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.fail(5000, "服务器内部错误，更新操作失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("update")
    public JsonResult<Object> update(@ApiParam(name = "users",value = "用户信息",required = true) @RequestBody Users users,
                                     @ApiParam(name = "token",value = "token",required = true) @RequestParam("token") String token){
        try{
            if(!JWTUtil.verify(token)){
                return JsonResult.fail(5001,"非法访问！！");
            }
            else{
                Users u1 = JWTUtil.parseToken(token);
                Users user = service.findUsers(u1.getUsername(),u1.getPwd());
                users.setId(user.getId());
                    int r = service.update(users);
                    return JsonResult.ok(r > 0);
            }
        }catch (Exception e){
            e.printStackTrace(); //打印
            return JsonResult.fail();
        }
    }
}
